﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;


namespace LsUpdater.API
{
    /// <summary>
    /// 文件传输类,上传下载,进度条显示等
    /// 作者:钟健 2011年2月16日17:00:21
    /// </summary>
    public class FTHelper
    {
        //申明


        public long Restbytes = 1;
        //public long downlength = 0;
        public long lastlength = 0;
        public long Downbytes = 0;//下载资源大小

        public long AllBytes = 0;//总块大小

        public event EventHandler DownloadComplete;
        public event EventHandler PreDownload;//准备下载事件
        public event EventHandler DownloadProcessing;//正在下载的事件

        public event EventHandler UpdateComplete;
        public static readonly FTHelper Instance = new FTHelper();

        public FTHelper()
        {
            //this.DownloadComplete += new EventHandler(FTHelper_DownloadComplete);
        }
        public void Download(string url, string dir)
        {
            if (!dir.EndsWith("/")) dir += "/";
            //dir = dir + "update/";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            //string url = "http://cn.bitcomet.com/bitcomet/bitcomet_setup.exe";
            //url = "http://cn.bitcomet.com/bitcomet/bitcomet_setup.exe";
            //url = "http://www.mou18.com/soft/update.zip";
            //url = "http://www.mou18.com/soft/都客音量调节助手(win7版).rar";
            AllBytes = GetFileSize(url);
            string FileName = url.Substring(url.LastIndexOf("/") + 1);
            string Location = dir + FileName + ".tmp!";
            //准备下载事件
            OnPreDownload(this, EventArgs.Empty);
            //判断下载的文件是否存在        
            if (File.Exists(dir + FileName))
            {
                //不下载直接解压
                FileInfo fileexist = new FileInfo(dir + FileName);
                if (fileexist.Length == AllBytes)
                {
                    //UpdateStep2(fileexist);
                    return;
                }
            }


            //打开上次下载的文件或新建文件 
            long lStartPos = 0;
            System.IO.FileStream fs = null;
            if (System.IO.File.Exists(Location))
            {
                try
                {
                    fs = System.IO.File.OpenWrite(Location);
                    lStartPos = fs.Length;
                    Downbytes = lStartPos;
                    fs.Seek(lStartPos, System.IO.SeekOrigin.Current); //移动文件流中的当前指针 
                }
                catch
                {
                    //可能不支持断点续传,删除临时文件重新下载
                    File.Delete(Location);
                    Download(url, dir);
                    return;
                }
            }
            else
            {
                fs = new System.IO.FileStream(Location, System.IO.FileMode.Create);
                lStartPos = 0;
            }

            //打开网络连接 
            try
            {
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
                if (lStartPos > 0)
                    request.AddRange((int)lStartPos); //设置Range值 

                //向服务器请求，获得服务器回应数据流 
                System.IO.Stream ns = request.GetResponse().GetResponseStream();
                Restbytes = request.GetResponse().ContentLength;

                byte[] nbytes = new byte[512];
                int nReadSize = 0;
                nReadSize = ns.Read(nbytes, 0, 512);
                Downbytes += nReadSize;//初始读入的下载字节
                while (nReadSize > 0)
                {
                    fs.Write(nbytes, 0, nReadSize);
                    nReadSize = ns.Read(nbytes, 0, 512);
                    Downbytes += nReadSize;

                    OnDownloadProcessing(this, EventArgs.Empty);//处理事件
                }

                fs.Close();
                ns.Close();
                FileInfo file = new FileInfo(Location);
                file.MoveTo(Location.Replace(".tmp!", ""));

                Console.WriteLine("下载完成");


                //timer1.Enabled = false;

                OnDownloadComplete(this, EventArgs.Empty);


          

                //开始安装.解压
                //如果进程没关.提示关闭



                //btnOK.Enabled = true;
                //btnCancel.Enabled = false;
                
            }
            catch (Exception ex)
            {
                fs.Close();
                //UpdateHelper.Instance.OnUpdateSuccess(this, EventArgs.Empty);
                //MessageBox.Show(ex.ToString());
                return;
                //
                //Console.WriteLine("下载过程中出现错误:" + ex.ToString());
            }

        }

        

        private void OnDownloadProcessing(object sender, EventArgs e)//升级失败的事件
        {
            if (DownloadProcessing != null)
            {
                DownloadProcessing(sender, e);
            }
        }

        private void OnDownloadComplete(object sender, EventArgs e)//升级失败的事件
        {
            if (DownloadComplete != null)
            {
                DownloadComplete(sender, e);
            }
        }
        private void OnPreDownload(object sender, EventArgs e)//准备下载事件
        {
            if (PreDownload != null)
            {
                PreDownload(sender, e);
            }
        }

        //private void OnDownloadComplete(object sender, EventArgs e)//升级完成
        //{
        //    if (DownloadComplete != null)
        //    {
        //        DownloadComplete(sender, e);
        //    }
        //}

        private void FTHelper_DownloadComplete(object sender, EventArgs e)
        {
           // System.Windows.Forms.MessageBox.Show(sender.ToString());
            //throw new NotImplementedException();
        }

        


        private static long GetFileSize(string url)
        {

            HttpWebResponse response = null;
            long size = -1;

            try
            {
                response = (HttpWebResponse)GetRequest(url).GetResponse();

                size = response.ContentLength;
            }
            catch
            {
                return 0;
            }
            finally
            {
                if (response != null)
                    response.Close();
            }
            return size;
        }
        private static HttpWebRequest GetRequest(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Credentials = CredentialCache.DefaultCredentials;
            return request;
        }






    }
}
